package com.nj.liandi.gulimall.ware.listener;

import com.nj.liandi.common.to.mq.OrderTo;
import com.nj.liandi.common.to.mq.StockLockedTo;
import com.nj.liandi.gulimall.ware.service.WareSkuService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;

/**
 * description: StockReleaseListener
 * date: 2021/11/4 11:34
 * author: maizj
 * version: 1.0
 */
@Service
@RabbitListener(queues = "stock.release.stock.queue")
public class StockReleaseListener {
    @Autowired
    WareSkuService wareSkuService;
    /** description: 库存自动解锁:下单成功,库存锁定,但是业务调用失败,导致订单不会滚,所以要实现库存自动解锁功能
     * version: 1.0
     * date: 2021/11/4 10:12
     * */
    @RabbitHandler
    public void handleStockLockedRelease(StockLockedTo to, Message message, Channel channel) throws IOException {
        System.out.println("收到解锁库存的消息");
        try {
           wareSkuService.unlockStock(to);
           channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
       }catch (Exception e){
           channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
       }
    }

    /** description: 订单关闭,解锁库存
     * version: 1.0
     * date: 2021/11/4 16:10
     * */
    @RabbitHandler
    public  void handleOrderCloseRelease(OrderTo orderTo, Message message, Channel channel) throws IOException {
        System.out.println("订单关闭准备解锁库存");
        try {
            wareSkuService.unlockStock(orderTo);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        }catch (Exception e){
            channel.basicReject(message.getMessageProperties().getDeliveryTag(),true);
        }
    }
}
